<template>
  <!-- 新增form -->
  <div>
    <el-form
      :rules="rules"
      ref="addNewForm"
      label-width="155px"
      label-position="right"
      :model="spojo"
      center
    >
      <el-form-item label="生产基地：">
        <!-- autocomplete="off"为 保存之前填过的值 -->
        <el-select clearable v-model="spojo.tProductBaseId" filterable placeholder="请选择所属公司">
          <el-option
            v-for="(item,index) in bNames"
            :key="index"
            :label="item.bName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="栽培面积（亩）：" prop="tCultivatedArea">
        <el-input v-model="spojo.tCultivatedArea" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="可采收面积（亩）：" prop="tReportableArea">
        <el-input v-model="spojo.tReportableArea" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="总产量（kg/年）：">
        <el-input v-model="spojo.tYield" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="种植环境：">
        <el-input v-model="spojo.tEnvironment" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="干/鲜比：">
        <el-input v-model="spojo.tProportion" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="价格/流通：">
        <el-input v-model="spojo.tPrice" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="采收时间">
        <el-input v-model="spojo.tCollecteTime" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="采收方法：">
        <el-input type="textarea" v-model="spojo.tCollecteMethod" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="净制：">
        <el-input type="textarea" v-model="spojo.tTotally" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="药用部位：">
        <el-input type="textarea" v-model="spojo.tPart" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="产地加工方法：">
        <el-input v-model="spojo.tProcess" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="分级与包装：">
        <el-input type="textarea" v-model="spojo.tScale" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="取样量及编号：">
        <el-input v-model="spojo.tSampleNum" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="植物标本编号：">
        <el-input v-model="spojo.tPlantNum" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="种繁模式：">
        <el-input v-model="spojo.tBreedMode" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="施肥方法：">
        <el-input v-model="spojo.tFertilizeMethod" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="病虫害防法：">
        <el-input v-model="spojo.tPestsPrecaution" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="药材质量：">
        <el-input
          class="medicinalQuality"
          placeholder="性状"
          v-model="spojo.tMedicinalSharp"
          autocomplete="off"
        ></el-input>
        <el-input
          class="medicinalQuality"
          placeholder="鉴别"
          v-model="spojo.tMedicinalIdentify"
          autocomplete="off"
        ></el-input>
        <el-input
          class="medicinalQuality"
          placeholder="浸出物"
          v-model="spojo.tMedicinalExtractum"
          autocomplete="off"
        ></el-input>
        <el-input
          class="medicinalQuality"
          placeholder="含量测定"
          v-model="spojo.tMedicinalContentsCheck"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="性状图片：">
        <el-upload
          action="none"
          :on-change="checkSharpType"
          accept="image/jpeg, image/jpg, image/png"
          :auto-upload="false"
          :on-remove="handleRemove"
          :file-list="fileListSharp"
          list-type="picture"
        >
          <el-button @click="cleanSharpImg" style="margin-top:10px" size="small" type="primary">选择图片</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="鉴别图片：">
        <el-upload
          ref="uploadImage"
          action="none"
          :on-change="checkIdentifyType"
          accept="image/jpeg, image/jpg, image/png"
          :auto-upload="false"
          :on-remove="handleRemove"
          :file-list="fileListIdentify"
          list-type="picture"
        >
          <el-button
            @click="cleanIdentifyImg"
            style="margin-top:10px"
            size="small"
            type="primary"
          >选择图片</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="特征图谱或指纹图谱：">
        <el-upload
          action="none"
          :on-change="checkFeatureType"
          accept="image/jpeg, image/jpg, image/png"
          :auto-upload="false"
          :on-remove="handleRemove"
          :file-list="fileListFeature"
          list-type="picture"
        >
          <el-button
            @click="cleanFeatureImg"
            style="margin-top:10px"
            size="small"
            type="primary"
          >选择图片</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="图谱说明：">
        <el-input
          type="textarea"
          rows="4"
          v-model="spojo.tMedicinalFeatureImgInfo"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="总评：">
        <el-select clearable v-model="spojo.tMedicinalQuality" placeholder="总体评价">
          <el-option label="优" value="优"></el-option>
          <el-option label="良" value="良"></el-option>
          <el-option label="合格" value="合格"></el-option>
          <el-option label="不合格" value="不合格"></el-option>
        </el-select>
        <!-- <el-input v-model="spojo.tMedicinalQuality" autocomplete="off"></!--> 
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import productbaseApi from "@/api/productbase";
import medicinalproductbaseApi from "@/api/medicinalproductbase";
import uuidv4 from "uuid/v4";
import qs from "qs";

export default {
  name: "add-new",
  props: {
    addnewData: {
      type: Object
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileListSharp: [],
      fileListIdentify: [],
      fileListFeature: [],
      sharpfile: null,
      identifyfile: null,
      featurefile: null,
      spojo: {
        id: "",
        tMedicinalId: "", // 药材的id
        tProductBaseId: "", // 基地的id
        tEnvironment: "", // 种植环境
        tCultivatedArea: "", //栽培面积
        tYield: "", // 总产量
        tProportion: "", // 干鲜比
        tReportableArea: "", //可采摘面积
        tPrice: "", //该药材的价格流通
        tCollecteTime: "", //采收时间
        tCollecteMethod: "", //采摘防法
        tTotally: "", // 净制
        tPart: "", // 该药材的选取部分
        tProcess: "", // 产地加工方法
        tScale: "", // 分级与包装
        tSampleNum: "", // 取样量及编号
        tPlantNum: "", // 植物标本编号
        tBreedMode: "", // 种繁模式
        tFertilizeMethod: "", // 施肥方式
        tPestsPrecaution: "", // 病虫害防法
        tMedicinalQuality: "", // 药材质量总评
        tMedicinalSharp: "", // 药材性状
        tMedicinalIdentify: "", // 药材鉴定
        tMedicinalExtractum: "", // 药材浸出物
        tMedicinalContentsCheck: "", // 药材含量检测
        tMedicinalSharpImgPath: "", // 该药材的性状图片的路径
        tMedicinalIdentifyImgPath: "", // 该药材的药材鉴定图片的路径
        tMedicinalFeatureImgPath: "", // 该药材的特征图谱或者是指纹图的路径
        tMedicinalSharpImgPathOut: "", // 该药材的性状图片的旧路径
        tMedicinalIdentifyImgPathOut: "", // 该药材的药材鉴定图片的旧路径
        tMedicinalFeatureImgPathOut: "", // 该药材的特征图谱或者是指纹图的旧路径
        tMedicinalFeatureImgInfo: "", //该药材的特征图的说明
        tCreateTime: "" // 创建时间
      }, //新增提交的数据
      rules: {
        //校验规则
        // bName: [
        //   //required: true为必填
        //   { required: true, message: "基地名称不能为空", trigger: "blur" }
        // ],
        tCultivatedArea: [
          //required: true为必填
          { required: true, message: "栽培面积不能为空", trigger: "blur" }
        ]
      },
      ischange: null,
      bNames: []
    };
  },

  // 因为不能直接修改props里的属性，所以不能直接addnewData通过v-model进行绑定
  // 在这里我们需要监听addnewData，当它发生变化时，立即将值赋给data中的spojo
  watch: {
    addnewData: {
      immediate: true,
      handler(val) {
        this.spojo = val;
      }
    },
    isEdit: {
      immediate: true,
      handler(val) {
        this.ischange = val;
      }
    }
  },

  created() {
    this.selectAllbNames();
  },

  mounted() {
    // props是单向数据流，通过触发update事件绑定addnewData，
    // 将data里的spojo指向父组件通过addnewData绑定的那个对象
    // 父组件在绑定addnewData的时候，需要加上.sync
    this.$emit("update:addnewData", this.spojo);
  },

  methods: {
    //查询产地列表
    selectAllbNames() {
      productbaseApi.selectAllName().then(resp => {
        this.bNames = resp.data;
      });
    },
    // 清空校验
    cancelFieldValidate(formName) {
      // 清空已选的图片
      this.cleanSharpImg();
      this.cleanIdentifyImg();
      this.cleanFeatureImg();
      this.$refs[formName].clearValidate();
    },

    // 检查图片类型
    checkSharpType(file, fileListSharp) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (fileType !== "jpeg" && fileType !== "jpg" && fileType !== "png") {
        this.$message.error("上传头像图片只能是 JPG 或 PNG格式!");
      }
      if (!isLt1M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      // 确认要上传的文件
      // 确认要上传的文件
      this.sharpfile = file;
      console.log("选择的图片" + this.sharpfile.name);
    },
    checkIdentifyType(file, fileListIdentify) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (fileType !== "jpeg" && fileType !== "jpg" && fileType !== "png") {
        this.$message.error("上传头像图片只能是 JPG 或 PNG格式!");
      }
      if (!isLt1M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      // 确认要上传的文件
      // 确认要上传的文件
      this.identifyfile = file;
      console.log("选择的图片" + this.identifyfile.name);
    },
    checkFeatureType(file, fileListFeature) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (fileType !== "jpeg" && fileType !== "jpg" && fileType !== "png") {
        this.$message.error("上传头像图片只能是 JPG 或 PNG格式!");
      }
      if (!isLt1M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      // 确认要上传的文件
      // 确认要上传的文件
      this.featurefile = file;
      console.log("选择的图片" + this.featurefile.name);
    },

    // 清空图片
    cleanSharpImg() {
      this.fileListSharp = [];
    },
    cleanIdentifyImg() {
      this.fileListIdentify = [];
    },
    cleanFeatureImg() {
      this.fileListFeature = [];
    },

    // 没啥用的，看看移除的图片信息
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    // 子组件校验表单
    validataForm() {
      this.spojo.tMedicinalSharpImgPathOut = this.spojo.tMedicinalSharpImgPath;
      this.spojo.tMedicinalIdentifyImgPathOut = this.spojo.tMedicinalIdentifyImgPath;
      this.spojo.tMedicinalFeatureImgPathOut = this.spojo.tMedicinalFeatureImgPath;
      // 提交药材质量中的3张图片
      // 性状
      let imgSharpFile = new FormData();
      let imgSharpPath = uuidv4().replace(/-/g, "");
      if (this.sharpfile) {
        this.spojo.tMedicinalSharpImgPath =
          imgSharpPath +
          "." +
          this.sharpfile.name.substring(
            this.sharpfile.name.lastIndexOf(".") + 1
          );
        imgSharpFile.append("file", this.sharpfile.raw);
        imgSharpFile.append("imgname", imgSharpPath);
      }

      // 鉴定
      let imgIdentifyFile = new FormData();
      let imgIdentifyPath = uuidv4().replace(/-/g, "");
      if (this.identifyfile) {
        this.spojo.tMedicinalIdentifyImgPath =
          imgIdentifyPath +
          "." +
          this.identifyfile.name.substring(
            this.identifyfile.name.lastIndexOf(".") + 1
          );
        imgIdentifyFile.append("file", this.identifyfile.raw);
        imgIdentifyFile.append("imgname", imgIdentifyPath);
      }

      // 特征谱图
      let imgFeatureFile = new FormData();
      let imgFeaturePath = uuidv4().replace(/-/g, "");
      if (this.featurefile) {
        this.spojo.tMedicinalFeatureImgPath =
          imgFeaturePath +
          "." +
          this.featurefile.name.substring(
            this.featurefile.name.lastIndexOf(".") + 1
          );
        imgFeatureFile.append("file", this.featurefile.raw);
        imgFeatureFile.append("imgname", imgFeaturePath);
      }

      this.$refs["addNewForm"].validate(valid => {
        if (valid) {
          //提交表单
          //上传性状图片
          if (this.sharpfile) {
            this.$ajax({
              method: "post",
              url: "/zy-api/item/medicinalProductBase/uploadTMedicinalSharpImg",
              data: imgSharpFile
            }).then(resp => {
              if (resp.data.code != true) {
                //失败
                this.$message({
                  message: "上传性状图片失败",
                  type: "warning"
                });
              }
            });
          }
          //上传鉴定图片
          if (this.identifyfile) {
            this.$ajax({
              method: "post",
              url:
                "/zy-api/item/medicinalProductBase/uploadTMedicinalIdentifyImg",
              data: imgIdentifyFile
            }).then(resp => {
              if (resp.data.code != true) {
                //失败
                this.$message({
                  message: "上传鉴定图片失败",
                  type: "warning"
                });
              }
            });
          }
          //上传特征谱图
          if (this.featurefile) {
            this.$ajax({
              method: "post",
              url:
                "/zy-api/item/medicinalProductBase/uploadTMedicinalFeatureImg",
              data: imgFeatureFile
            }).then(resp => {
              if (resp.data.code != true) {
                //失败
                this.$message({
                  message: "上传特征谱图片失败",
                  type: "warning"
                });
              }
            });
          }
          this.spojo.tMedicinalId = localStorage.getItem("id");
          if (this.ischange) {
            console.log(JSON.stringify(this.spojo));
            medicinalproductbaseApi.productBaseUpdate(this.spojo).then(resp => {
              if (resp.data.code == 0) {
                // 修改成功
                this.$message({
                  message: "修改产地信息成功",
                  type: "success"
                });
                // 刷新数据
                this.$emit("fetchData");
                // 关闭
                this.$emit("close");
              } else {
                // 失败
                this.$message({
                  message: "修改产地信息失败",
                  type: "warning"
                });
              }
            });
          } else {
            console.log(JSON.stringify(this.spojo));
            medicinalproductbaseApi.productBaseInsert(this.spojo).then(resp => {
              if (resp.data.code == 0) {
                // 修改成功
                this.$message({
                  message: "新增产地信息成功",
                  type: "success"
                });
                // 刷新数据
                this.$emit("fetchData");
                // 关闭
                this.$emit("close");
              } else {
                // 失败
                this.$message({
                  message: "新增产地信息失败",
                  type: "warning"
                });
              }
            });
          }
        } else {
          this.$message({
            message: "提交表单失败",
            type: "warning"
          });
          return false;
        }
      });
    }
  }
};
</script>

<style lang="css" scoped>
.medicinalQuality {
  margin-top: 5px;
}
</style>